﻿using ZyGames.DZPocker.Model;
using ZyGames.Framework.Game.Contract;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.DZPocker.Tools;
using ZyGames.Framework.Common.Serialization;
using System;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 玩家申请上局回顾
	/// </summary>
	public class Action30047 : BaseAction
	{
		private int tableId;

		private TableData _currentTable;
		private GameUser _currentGameUser;
		private string _recordStr = string.Empty;
		private string _tableCardsStr = string.Empty;
		private string _userCardsStr = string.Empty;
		private string _userWinChipStr = string.Empty;
		private int _hand;
		private int _savedCount = 0;
		private int _userId;
		private int _maxHand = 0;

		public Action30047(HttpGet actionGetter)
			: base((short)ActionType.DZApplyReviewByHand, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetInt("TableID", ref tableId) &&
				httpGet.GetInt("UserID", ref _userId) &&
				httpGet.GetInt("Hand", ref _hand))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			_currentTable = GameRoom.Current.GetTableData(tableId);
			if (_currentTable == null)
			{
				Tool.WriteWarmingLine("消息30047获得房间不存在");
				return false;
			}

			_maxHand = _currentTable.GetCurrentMaxRecordHand();
			if(_hand > _maxHand)
			{
				Tool.WriteErrorLine("请求超出");
				return true;
			}
			if(_hand == 0)
			{
				_hand = _maxHand;
			}
			var recordPair = _currentTable.GetRecordByHand(_hand);
			if (recordPair.Key == null)
			{
				Tool.WriteErrorLine("消息30047 没有玩家的下注记录");
				return false;
			}
			var userHandRecord = _currentTable.GetUserHandScoreByHand(_hand);
			if (userHandRecord.Key == null)
			{
				Tool.WriteErrorLine("消息30047 没有玩家的手牌记录");
				return false;
			}
			this._recordStr = Convert.ToBase64String(ProtoBufUtils.Serialize(recordPair.Value));  //List<SharedUserBetRecords>
			this._tableCardsStr = Convert.ToBase64String(ProtoBufUtils.Serialize(recordPair.Key));  //SharedTableCards
			this._userCardsStr = Convert.ToBase64String(ProtoBufUtils.Serialize(userHandRecord.Key));  //Dictionary<SimpleUserData, List<int>>
			this._userWinChipStr = Convert.ToBase64String(ProtoBufUtils.Serialize(userHandRecord.Value)); //上局玩家获胜的筹码  包括保险人 也包括输掉的人


			this._savedCount = GameTable.Current.UserSavedCount(_userId);
			return true;
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(this._currentTable.TableLogicID);
			this.PushIntoStack(this._recordStr);
			this.PushIntoStack(this._tableCardsStr);
			this.PushIntoStack(this._userCardsStr);
			this.PushIntoStack(this._userWinChipStr);
			this.PushIntoStack(this._hand);
			this.PushIntoStack(this._savedCount);
			this.PushIntoStack(this._maxHand);
		}
	}
}
